<template>
  <el-dialog custom-class="c_dialog" v-model="dialogInfo.visible" :title="title" width="600px" :before-close="cancelHandel">
    <template #title>
      <div class="dialog_header">{{ title }}</div>
    </template>
    <el-form label-width="80px" ref="ruleFormRef" :model="formData" :rules="rules">
      <el-form-item label="阶段名称" prop="name">
        <el-input maxlength="15" show-word-limit v-model="formData.name" placeholder="请输入阶段名称"></el-input>
      </el-form-item>
      <el-form-item label="阶段描述" prop="desc">
        <el-input maxlength="150" show-word-limit v-model="formData.desc" type="textarea" placeholder="请输入阶段描述"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="footer-box">
        <div>默认将会添加至【{{ props.tip }}】客户阶段之前</div>
        <div>
          <el-button @click="cancelHandel">取消</el-button>
          <el-button type="primary" @click="submitHandel">确定</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import Dialog from '@/components/Dialog.vue'
  import { ref, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import { stageCreate, stageEdit } from '../../api'
  const apiArr = [stageCreate, stageEdit]
  const ruleFormRef = ref(null)
  const props = defineProps(['tip'])
  const emit = defineEmits(['refresh'])
  const formData = ref({
    name: '',
    desc: '',
    cust_stage_id: ''
  })
  const title = ref('新增客户阶段')
  const rules = ref({
    title: { required: true, message: '请输入阶段名称' }
  })
  const dialogInfo = ref({
    visible: false,
    editInfo: {} //编辑的数据
  })

  const cancelHandel = () => {
    dialogInfo.value.visible = false
  }

  const submitHandel = () => {
    if (!formData.value.name) {
      ElMessage.error('请输入阶段名称')
      return
    }
    apiArr[formData.value.cust_stage_id ? 1 : 0](formData.value).then((r: any) => {
      ElMessage.success(formData.value.cust_stage_id ? '编辑成功' : '创建成功')
      emit('refresh')
      dialogInfo.value.visible = false
    })
  }

  watch(
    () => dialogInfo.value.visible,
    (val) => {
      console.log(val, 6666)
      if (val) {
        let { name, desc, id } = dialogInfo.value.editInfo
        if (id) {
          title.value = '编辑客户阶段'
          formData.value = {
            name,
            desc,
            cust_stage_id: id
          }
        } else {
          title.value = '新增客户阶段'
          formData.value = {
            name: '',
            desc: '',
            cust_stage_id: ''
          }
        }
      }
    }
  )

  defineExpose({ dialogInfo })
</script>

<style lang="scss" scoped>
  .footer-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #33302d;
  }
</style>
